package constant.milk.toilet.database;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DbCreateQuery
{
	private SQLiteDatabase db;
	
	public DbCreateQuery(SQLiteDatabase db)
	{
		this.db = db;
	}
	
	public boolean createTimerListTable()
	{
		String sql = "CREATE TABLE " + TableName.TIMER_LIST + " (" +
						"id integer PRIMARY KEY autoincrement," +
						"year integer NOT NULL DEFAULT 0," + // 년
						"month integer NOT NULL DEFAULT 0," + // 월
						"day integer NOT NULL DEFAULT 0," + // 일
						"starttime text NOT NULL DEFAULT '0'," + // 시작시간
						"term text NOT NULL DEFAULT '0');"; // 경과시간

		if (!isTable(db, TableName.TIMER_LIST))
		{
			db.execSQL(sql);
			
			return true;
		}
		else
		{
			return false;
		}
	}
	
	public boolean createStickerTable()
	{
		// 0 = 없음, 1 = 최고, 2 = 만족, 3 = 왔다갔다, 4 = 잠잠, 5 = 찜찜, 6 = 불쾌, 7 = 나쁨, 8 = 설사, 9 = 토끼똥
		String sql = "CREATE TABLE " + TableName.STICKER_LIST + " (" +
						"id integer PRIMARY KEY autoincrement," +
						"year integer NOT NULL DEFAULT 0," + // 년
						"month integer NOT NULL DEFAULT 0," + // 월
						"day integer NOT NULL DEFAULT 0," + // 일
						"sticker integer NOT NULL DEFAULT 0);"; // 스티커

		if (!isTable(db, TableName.STICKER_LIST))
		{
			db.execSQL(sql);
			
			return true;
		}
		else
		{
			return false;
		}
	}
	
	/**
	 * 테이블이 있는지 없는지 확인한다.
	 * @param db
	 * @param tableName
	 * @return
	 */
	private boolean isTable(SQLiteDatabase db, String tableName)
	{
		String query = "SELECT tbl_name FROM sqlite_master WHERE tbl_name = '" + tableName + "'";
		Cursor c;
		try
		{
			c = db.rawQuery(query, null);
		} catch (Exception e)
		{
			return false;
		}
		
		if (c.getCount() > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}
